#! /usr/bin/python2.5
#
# TODO: This program use for start/stop/restart server
#		or initial the database or run tests
#
import os
import signal
import sys

from common import config
from server import Server

def startServer():
    if os.access(config.PID_FILE, os.R_OK):
        print "ERROR: NuclearIndustry server has already started"
        sys.exit()
    pid = os.fork()
    if not pid:
        """Child thread"""
        pid = os.getpid()
        pid_file = file(config.PID_FILE, 'w')
        pid_file.write(str(pid) + "\n")
        pid_file.close()
        server = Server()
        print "Server start ... ..."
        server.start_server()

def stopServer():
    if os.access(config.PID_FILE, os.R_OK):
        pid_file = file(config.PID_FILE, 'r')
        pid = int(pid_file.readline().strip())
        pid_file.close()
        os.kill(pid, signal.SIGTERM)
        os.unlink(config.PID_FILE)
        print "Server stop ... ..."
    else:
        print "ERROR: NuclearIndustry server has not started"

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print """
===========================================================
Usage: nuclearindustry OPTION

    OPTION:
        restart:    Restart the NuclearIndustry server
        start:      Start the NuclearIndustry server
        stop:       Stop the NuclearIndustry server
===========================================================
        """
        sys.exit()

    if sys.argv[1] == "start":
        startServer()
    elif sys.argv[1] == "stop":
        stopServer()
    elif sys.argv[1] == "restart":
        stopServer()
        startServer()
    elif sys.argv[1] == "initdb":
        pass
        

